<template>
  <el-dialog
    v-model="dialogVisible"
    title="规则设置"
    width="800px"
    :close-on-click-modal="false"
  >
    <el-tabs v-model="activeTab" type="border-card">
      <!-- 执行设置 -->
      <el-tab-pane label="执行设置" name="execution">
        <el-form :model="settingsForm" :rules="rules" ref="settingsFormRef" label-width="120px">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="执行超时" prop="timeout">
                <el-input-number
                  v-model="settingsForm.timeout"
                  :min="1"
                  :max="3600"
                  placeholder="秒"
                  style="width: 100%"
                />
                <div class="form-tip">规则执行的最大等待时间，超时将终止执行</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="重试次数" prop="retryCount">
                <el-input-number
                  v-model="settingsForm.retryCount"
                  :min="0"
                  :max="10"
                  placeholder="次"
                  style="width: 100%"
                />
                <div class="form-tip">执行失败时的重试次数</div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="冷却时间" prop="cooldown">
                <el-input-number
                  v-model="settingsForm.cooldown"
                  :min="0"
                  :max="86400"
                  placeholder="秒"
                  style="width: 100%"
                />
                <div class="form-tip">规则执行后的冷却时间，期间不会再次触发</div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最大触发次数" prop="maxTriggers">
                <el-input-number
                  v-model="settingsForm.maxTriggers"
                  :min="0"
                  placeholder="次"
                  style="width: 100%"
                />
                <div class="form-tip">规则的最大触发次数，0表示无限制</div>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="并发控制" prop="concurrency">
            <el-switch
              v-model="settingsForm.concurrency"
              active-text="允许并发执行"
              inactive-text="禁止并发执行"
            />
            <div class="form-tip">是否允许同一规则的多个实例同时执行</div>
          </el-form-item>

          <el-form-item label="失败处理" prop="failureAction">
            <el-radio-group v-model="settingsForm.failureAction">
              <el-radio label="ignore">忽略失败</el-radio>
              <el-radio label="retry">自动重试</el-radio>
              <el-radio label="disable">禁用规则</el-radio>
              <el-radio label="notify">发送通知</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 触发设置 -->
      <el-tab-pane label="触发设置" name="trigger">
        <el-form :model="settingsForm" label-width="120px">
          <el-form-item label="触发模式" prop="triggerMode">
            <el-radio-group v-model="settingsForm.triggerMode">
              <el-radio label="realtime">实时触发</el-radio>
              <el-radio label="batch">批量触发</el-radio>
              <el-radio label="scheduled">定时触发</el-radio>
            </el-radio-group>
          </el-form-item>

          <el-form-item label="批量大小" prop="batchSize" v-if="settingsForm.triggerMode === 'batch'">
            <el-input-number
              v-model="settingsForm.batchSize"
              :min="1"
              :max="1000"
              placeholder="条"
              style="width: 200px"
            />
            <div class="form-tip">批量处理时的数据条数</div>
          </el-form-item>

          <el-form-item label="定时表达式" prop="cronExpression" v-if="settingsForm.triggerMode === 'scheduled'">
            <el-input
              v-model="settingsForm.cronExpression"
              placeholder="0 0 * * * ?"
              style="width: 300px"
            />
            <el-button type="text" @click="showCronHelper">表达式帮助</el-button>
            <div class="form-tip">使用Cron表达式定义触发时间</div>
          </el-form-item>

          <el-form-item label="触发条件" prop="triggerCondition">
            <el-select v-model="settingsForm.triggerCondition" placeholder="请选择触发条件" style="width: 300px">
              <el-option label="数据变化时" value="dataChange" />
              <el-option label="阈值超限时" value="threshold" />
              <el-option label="设备上线时" value="deviceOnline" />
              <el-option label="设备离线时" value="deviceOffline" />
              <el-option label="告警产生时" value="alarmGenerated" />
            </el-select>
          </el-form-item>

          <el-form-item label="数据过滤" prop="dataFilter">
            <el-input
              v-model="settingsForm.dataFilter"
              type="textarea"
              :rows="4"
              placeholder="输入数据过滤条件，支持JavaScript表达式"
            />
            <div class="form-tip">用于过滤触发数据的条件表达式</div>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 通知设置 -->
      <el-tab-pane label="通知设置" name="notification">
        <el-form :model="settingsForm" label-width="120px">
          <el-form-item label="启用通知" prop="enableNotification">
            <el-switch
              v-model="settingsForm.enableNotification"
              active-text="开启"
              inactive-text="关闭"
            />
          </el-form-item>

          <template v-if="settingsForm.enableNotification">
            <el-form-item label="通知方式" prop="notificationMethods">
              <el-checkbox-group v-model="settingsForm.notificationMethods">
                <el-checkbox label="email">邮件通知</el-checkbox>
                <el-checkbox label="sms">短信通知</el-checkbox>
                <el-checkbox label="webhook">Webhook</el-checkbox>
                <el-checkbox label="dingtalk">钉钉通知</el-checkbox>
              </el-checkbox-group>
            </el-form-item>

            <el-form-item label="通知级别" prop="notificationLevel">
              <el-radio-group v-model="settingsForm.notificationLevel">
                <el-radio label="all">所有事件</el-radio>
                <el-radio label="success">仅成功</el-radio>
                <el-radio label="failure">仅失败</el-radio>
                <el-radio label="error">仅错误</el-radio>
              </el-radio-group>
            </el-form-item>

            <el-form-item label="通知模板" prop="notificationTemplate">
              <el-input
                v-model="settingsForm.notificationTemplate"
                type="textarea"
                :rows="4"
                placeholder="通知消息模板，支持变量替换"
              />
              <div class="form-tip">
                可用变量: ${ruleName}, ${status}, ${result}, ${executeTime}
              </div>
            </el-form-item>

            <el-form-item label="通知频率" prop="notificationFrequency">
              <el-select v-model="settingsForm.notificationFrequency" style="width: 200px">
                <el-option label="每次都通知" value="always" />
                <el-option label="每小时最多1次" value="hourly" />
                <el-option label="每天最多1次" value="daily" />
                <el-option label="仅首次通知" value="once" />
              </el-select>
            </el-form-item>
          </template>
        </el-form>
      </el-tab-pane>

      <!-- 日志设置 -->
      <el-tab-pane label="日志设置" name="logging">
        <el-form :model="settingsForm" label-width="120px">
          <el-form-item label="启用日志" prop="enableLogging">
            <el-switch
              v-model="settingsForm.enableLogging"
              active-text="开启"
              inactive-text="关闭"
            />
          </el-form-item>

          <template v-if="settingsForm.enableLogging">
            <el-form-item label="日志级别" prop="logLevel">
              <el-select v-model="settingsForm.logLevel" style="width: 200px">
                <el-option label="DEBUG" value="debug" />
                <el-option label="INFO" value="info" />
                <el-option label="WARN" value="warn" />
                <el-option label="ERROR" value="error" />
              </el-select>
            </el-form-item>

            <el-form-item label="日志保留" prop="logRetention">
              <el-input-number
                v-model="settingsForm.logRetention"
                :min="1"
                :max="365"
                placeholder="天"
                style="width: 200px"
              />
              <span style="margin-left: 10px">天</span>
              <div class="form-tip">日志文件的保留天数</div>
            </el-form-item>

            <el-form-item label="详细日志" prop="detailedLogging">
              <el-switch
                v-model="settingsForm.detailedLogging"
                active-text="记录详细信息"
                inactive-text="仅记录关键信息"
              />
            </el-form-item>

            <el-form-item label="日志格式" prop="logFormat">
              <el-radio-group v-model="settingsForm.logFormat">
                <el-radio label="json">JSON格式</el-radio>
                <el-radio label="text">文本格式</el-radio>
              </el-radio-group>
            </el-form-item>
          </template>
        </el-form>
      </el-tab-pane>
    </el-tabs>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleReset">重置</el-button>
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSave" :loading="saving">保存设置</el-button>
      </div>
    </template>

    <!-- Cron表达式帮助对话框 -->
    <el-dialog v-model="cronHelperVisible" title="Cron表达式帮助" width="600px">
      <div class="cron-helper">
        <h4>Cron表达式格式：秒 分 时 日 月 周</h4>
        <el-table :data="cronExamples" style="width: 100%">
          <el-table-column prop="expression" label="表达式" width="150" />
          <el-table-column prop="description" label="说明" />
        </el-table>
        
        <h4 style="margin-top: 20px">特殊字符说明：</h4>
        <ul class="cron-symbols">
          <li><code>*</code> - 匹配任意值</li>
          <li><code>?</code> - 不指定值（仅用于日和周）</li>
          <li><code>-</code> - 范围，如 1-5</li>
          <li><code>,</code> - 列举，如 1,3,5</li>
          <li><code>/</code> - 步长，如 */5 表示每5个单位</li>
        </ul>
      </div>
      
      <template #footer>
        <el-button @click="cronHelperVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, computed, watch } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'

// Props
interface Props {
  visible: boolean
  ruleData?: any
}

const props = withDefaults(defineProps<Props>(), {
  visible: false,
  ruleData: () => ({})
})

// Emits
const emit = defineEmits(['update:visible', 'save'])

// 响应式数据
const activeTab = ref('execution')
const saving = ref(false)
const cronHelperVisible = ref(false)
const settingsFormRef = ref()

// 设置表单数据
const settingsForm = reactive({
  // 执行设置
  timeout: 30,
  retryCount: 3,
  cooldown: 0,
  maxTriggers: 0,
  concurrency: false,
  failureAction: 'retry',
  
  // 触发设置
  triggerMode: 'realtime',
  batchSize: 100,
  cronExpression: '0 0 * * * ?',
  triggerCondition: 'dataChange',
  dataFilter: '',
  
  // 通知设置
  enableNotification: false,
  notificationMethods: [],
  notificationLevel: 'failure',
  notificationTemplate: '规则 ${ruleName} 执行${status}，结果：${result}',
  notificationFrequency: 'always',
  
  // 日志设置
  enableLogging: true,
  logLevel: 'info',
  logRetention: 30,
  detailedLogging: false,
  logFormat: 'json'
})

// 表单验证规则
const rules = {
  timeout: [
    { required: true, message: '请输入执行超时时间', trigger: 'blur' },
    { type: 'number', min: 1, max: 3600, message: '超时时间必须在1-3600秒之间', trigger: 'blur' }
  ],
  retryCount: [
    { required: true, message: '请输入重试次数', trigger: 'blur' },
    { type: 'number', min: 0, max: 10, message: '重试次数必须在0-10次之间', trigger: 'blur' }
  ]
}

// Cron表达式示例
const cronExamples = [
  { expression: '0 0 * * * ?', description: '每小时执行一次' },
  { expression: '0 0 0 * * ?', description: '每天0点执行' },
  { expression: '0 0 12 * * ?', description: '每天12点执行' },
  { expression: '0 0/30 * * * ?', description: '每30分钟执行一次' },
  { expression: '0 0 0 1 * ?', description: '每月1号0点执行' },
  { expression: '0 0 0 ? * MON', description: '每周一0点执行' }
]

// 计算属性
const dialogVisible = computed({
  get: () => props.visible,
  set: (value) => emit('update:visible', value)
})

// 监听规则数据变化
watch(() => props.ruleData, (newData) => {
  if (newData && Object.keys(newData).length > 0) {
    // 从规则数据中加载设置
    Object.assign(settingsForm, {
      timeout: newData.timeout || 30,
      retryCount: newData.retryCount || 3,
      cooldown: newData.cooldown || 0,
      maxTriggers: newData.maxTriggers || 0,
      // ... 其他设置
    })
  }
}, { immediate: true })

// 方法
const showCronHelper = () => {
  cronHelperVisible.value = true
}

const handleSave = async () => {
  try {
    await settingsFormRef.value?.validate()
    saving.value = true
    
    // 模拟保存操作
    await new Promise(resolve => setTimeout(resolve, 1000))
    
    emit('save', { ...settingsForm })
    ElMessage.success('设置保存成功')
    handleClose()
  } catch (error) {
    ElMessage.error('请检查表单输入')
  } finally {
    saving.value = false
  }
}

const handleReset = async () => {
  try {
    await ElMessageBox.confirm('确定要重置所有设置吗？', '确认重置', {
      type: 'warning'
    })
    
    // 重置为默认值
    Object.assign(settingsForm, {
      timeout: 30,
      retryCount: 3,
      cooldown: 0,
      maxTriggers: 0,
      concurrency: false,
      failureAction: 'retry',
      triggerMode: 'realtime',
      batchSize: 100,
      cronExpression: '0 0 * * * ?',
      triggerCondition: 'dataChange',
      dataFilter: '',
      enableNotification: false,
      notificationMethods: [],
      notificationLevel: 'failure',
      notificationTemplate: '规则 ${ruleName} 执行${status}，结果：${result}',
      notificationFrequency: 'always',
      enableLogging: true,
      logLevel: 'info',
      logRetention: 30,
      detailedLogging: false,
      logFormat: 'json'
    })
    
    ElMessage.success('设置已重置')
  } catch (error) {
    // 用户取消重置
  }
}

const handleClose = () => {
  emit('update:visible', false)
}
</script>

<style scoped>
.form-tip {
  font-size: 12px;
  color: #909399;
  margin-top: 4px;
  line-height: 1.4;
}

.dialog-footer {
  text-align: right;
}

.cron-helper h4 {
  margin: 0 0 15px 0;
  color: #303133;
}

.cron-symbols {
  margin: 0;
  padding-left: 20px;
}

.cron-symbols li {
  margin-bottom: 8px;
  line-height: 1.5;
}

.cron-symbols code {
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', monospace;
  color: #e6a23c;
}

:deep(.el-tabs__content) {
  padding: 20px;
}

:deep(.el-form-item__label) {
  font-weight: 500;
}

:deep(.el-checkbox-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-radio-group) {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

:deep(.el-input-number) {
  width: 100%;
}
</style>